/* ###################################### */
/* ###     Util Engine, by Kalith    ### */
/* ###################################### */
/*            LuaManager source           */
/*                                        */
/*                                        */

#include "LuaManager.h"
#include "LuaState.h"
#include "Stdhelper.h"

using namespace std;

namespace Util
{
    const Str LuaManager::CLASS_NAME = "LuaManager";

    LuaManager::LuaManager()
    {
    }

    LuaManager::~LuaManager()
    {
        Map< lua_State*, Ptr<Lua::State> >::iterator iter;
        foreach (iter, lLuaStateList_)
        {
            iter->second.Delete();
        }
    }

    Ptr<Lua::State> LuaManager::CreateLua()
    {
        #ifdef USING_THREADS
        Lock l(mMutex_);
        #endif

        Ptr<Lua::State> pLua = new Lua::State();
        lLuaStateList_[pLua->GetState()] = pLua;
        return pLua;
    }

    void LuaManager::CloseLua( Ptr<Lua::State> pLua )
    {
        if (pLua)
        {
            #ifdef USING_THREADS
            Lock l(mMutex_);
            #endif

            Map< lua_State*, Ptr<Lua::State> >::iterator iter;
            iter = lLuaStateList_.Get(pLua->GetState());
            if (iter != lLuaStateList_.End())
            {
                iter->second.Delete();
                lLuaStateList_.Erase(iter);
            }
        }
    }

    Ptr<Lua::State> LuaManager::GetState( lua_State* pLua ) const
    {
        Map< lua_State*, Ptr<Lua::State> >::const_iterator iter;
        iter = lLuaStateList_.Get(pLua);
        if (iter != lLuaStateList_.End())
        {
            return iter->second;
        }
        else
            return nullptr;
    }

    Ptr<Lua::State> LuaManager::GetDefaultLua() const
    {
        return pDefaultLua_;
    }

    void LuaManager::SetDefaultLua( Ptr<Lua::State> pLua )
    {
        pDefaultLua_ = pLua;
    }
}

